1. Database Setup mongo atlas

1. Setting Up MongoDB with MongoDB Atlas

Follow these steps to set up MongoDB Atlas for your project.

  1. Login to MongoDB Atlas
    Register or log in to MongoDB Atlas here: MongoDB Atlas | MongoDB.

  2. Create a New Project

    • After logging in, click on Create New Project.
    • Enter a project name, click Next, and then Create Project.
  3. Create a New Deployment

    • Go to Deployment.
    • Choose Create New Deployment and select the Free option.
    • Select the Mumbai/India server (or choose another location based on your preference).
  4. Configure Security Quick Start

    a. Database Access (Username & Password)

    • Create a username and password, for example:
      • Username: aakash
      • Password: 223
    • Click Create User and assign the built-in role readWriteAnyDatabase for full read and write access.

    b. Choose Connection Environment

    • When prompted with "Where would you like to connect?", select "Local Environment".

    c. Network Access (IP Whitelisting)

    • Go to Network Access.
    • Add an IP address for access; enter 0.0.0.0/0 to allow access from anywhere, then click Add Entry.
  5. Get the Connection String

    • Go to Database Deployments.
    • In Cluster0, click Connect > Compass.
    • Copy the connection string provided for MongoDB Compass or MongoDB URI for use in your project.

![[../attachments/mongodb_atlas.mp4]]


2. Implementing MongoDB in the Backend to connect with Frontend

we created a folder structure like this which will handle the whole project

attachments/Pasted image 20241112151707.png| 200

1. Setting Up the .env File

.env

 PORT= 8000
 MONGODB_URI= mongodb+srv://sanskarbhushankar01:password@cluster0.m8o04.mongodb.net

2. Setting Up src/constant.js

src/constant.js

export const DB_NAME = "onlyTube";

3. Code to Connect MongoDB with Mongoose

src/db/index.js

import mongoose from 'mongoose';
import { DB_NAME } from "../constant.js";

const connectionDB = async () => {
    try {
        const connectionInstance = await mongoose.connect(`${process.env.MONGO_URI}/${DB_NAME}`);
        console.log(`MongoDB connected on host ${connectionInstance.connection.host}`);
    } catch (error) {
        console.log("Connection Error:", error);
        process.exit(1);
    }
};

export default connectionDB;

4. Import and Call the Database Connection in index.js

backend/index.js

import connectionDB from "./db/index.js";
import dotenv from 'dotenv';

dotenv.config({
    path: "./.env"
});

connectionDB();

and run npm run dev